package handler

import (
	"context"
	"fmt"
	"goodProject_srv/global"
	"goodProject_srv/model"
	"goodProject_srv/proto"
)

type GoodsServer struct{}

/*
*

		@Author fuyx
	 	@Text 商品新增
		@Request proto
	    @Return data
*/
func (s *GoodsServer) InsertGoods(ctx context.Context, req *proto.InsertRequest) (*proto.ResultResponse, error) {
	userInfoRsp := RsponseToModel(req)
	result := global.DB.Create(&userInfoRsp)
	if result.Error != nil {
		return nil, result.Error
	}
	rsp := &proto.ResultResponse{
		Code:    200,
		Success: true,
		Msg:     "请求成功",
	}
	return rsp, nil
}

// 图表接口
func (s *GoodsServer) GetStaticBySearch(ctx context.Context, req *proto.StatisticsRequest) (*proto.ResultDataResponse, error) {
	var order []model.Order
	//先做条件判断
	if req.Options == 1 {
		rsp := &proto.ResultDataResponse{}
		//个人排行
		result := global.DB.Distinct("user_id").Joins("User").Find(&order)
		fmt.Println(result)
		for _, v := range order {
			var resultCount int64
			global.DB.Table("order").Where("user_id = ?", v.UserId).Count(&resultCount)
			userCountRep := UserModelToRsponse(v, resultCount)
			rsp.Data = append(rsp.Data, &userCountRep)

		}
		return rsp, nil
	} else {
		//部门排行

	}
	return nil, nil
}

func UserModelToRsponse(order model.Order, count int64) proto.ResultByStatisticsResponse {
	result := proto.ResultByStatisticsResponse{
		OrderCount: count,
		UserName:   order.User.Name,
	}

	return result
}

/*
*
@Author fuyx
@Text 商品列表
@Request proto
@Return data
*/
func (s *GoodsServer) GoodList(ctx context.Context, req *proto.SearchRequest) (*proto.ReturnDataResponse, error) {
	//var orders []model.Order
	//result := global.DB.Preload("User").Find(&orders)
	//fmt.Println(orders[0].User.Name) // 输出第一条数据的用户名

	var good []model.Goods
	//查询商品数据
	//result := global.DB.Find(&goods)
	//模型关联
	//result := global.DB.Preload("Brand").Find(&good)
	//通过joins联查
	result := global.DB.Joins("Brand").Find(&good)
	if result.Error != nil {
		return nil, result.Error
	}
	rsp := &proto.ReturnDataResponse{}

	//global.DB.Scopes(Paginate(int(req.Pn), int(req.PSize))).Find(&users)
	//
	//for _, good := range goods {
	//	//userInfoRsp := ModelToRsponse(good)
	//	//rsp.Data = append(rsp.Data, &userInfoRsp)
	//	//var brand model.Brand
	//	//global.DB.Select("name").Where("id=?", good.ID).First(&brand)
	//}
	return rsp, nil
}

func RsponseToModel(request *proto.InsertRequest) model.Goods {
	userInfoRsp := model.Goods{
		GoodName:    request.GoodsName,
		GoodBrand:   int(request.GoodBrand),
		GoodClassId: int(request.GoodClassId),
		GoodMenu:    int(request.GoodMenu),
		GoodPic:     request.GoodPic,
		Price:       request.Price,
	}
	return userInfoRsp
}

//func ModelToRsponse(goods model.Goods) proto.ReturnDataResponse {
//	result := proto.ReturnDataResponse{
//		GoodsName: goods.GoodName,
//		GoodPic: goods.GoodPic,
//
//	}
//}
